/*
 * @Autor: Ruohong Yu
 * @Date: 2023-02-23 10:41:09
 * @Description: file content
 * @FilePath: \ebookd:\program\vsc\ebook\node-ebook\utils\voice.js
 */
const CryptoJS = require('crypto-js')
const WebSocket = require('ws')
var log = require('log4node')
const mp3FilePath = require('../bin/const').mp3FilePath
const BaseUrl = require('../bin/const').BaseUrl
var fs = require('fs')


const fileName = 'voice'
const filePath = `${mp3FilePath}/${fileName}.mp3`
const downloadUrl = `${BaseUrl}/public/mp3/${fileName}.mp3`

// 系统配置 
let config = {
  // 请求地址
  hostUrl: "wss://tts-api.xfyun.cn/v2/tts",
  host: "tts-api.xfyun.cn",
  //在控制台-我的应用-在线语音合成（流式版）获取
  appid: "c21b5326",
  //在控制台-我的应用-在线语音合成（流式版）获取
  apiSecret: "NjBmOWNmYTJkNWE1ZWVlNzMwODNmZTkx",
  //在控制台-我的应用-在线语音合成（流式版）获取
  apiKey: "05329df1c2dd798192031962c919577a",
  text: "Earth and Planetary Sciences10.1007/978-3-319-13764-3_11. Wetlands and Water Framework Directive",
  uri: "/v2/tts",
}

function createVoice(req,res){
  // 获取当前时间 RFC1123格式
  let date = (new Date().toUTCString())
  // 设置当前临时状态为初始化
  let wssUrl = config.hostUrl + "?authorization=" + getAuthStr(date) + "&date=" + date + "&host=" + config.host
  let ws = new WebSocket(wssUrl)
  // config.text=req.query.text
  console.log(config.text)
  // 连接建立完毕，读取数据进行识别
  ws.on('open', () => {
    log.info("websocket connect!")
    let frame = {
      // 填充common
      "common": {
          "app_id": config.appid
      },
      // 填充business
      "business": {
          "aue": "lame",
          "sfl": 1,
          "auf": "audio/L16;rate=16000",
          "vcn": "xiaoyan",
          "tte": "UTF8"
      },
      // 填充data
      "data": {
          "text": Buffer.from(config.text).toString('base64'),
          "status": 2
      }
    }
    // 如果之前保存过音频文件，删除之
    if (fs.existsSync(filePath)) {
      fs.unlink(filePath, (err) => {
          if (err) {
              log.error('remove error: ' + err)   
          }
      })
    }
    ws.send(JSON.stringify(frame))
  })

  // 得到结果后进行处理，仅供参考，具体业务具体对待
  ws.on('message', (data, err) => {
    if (err) {
        log.error('message error: ' + err)
        return
    }

    let xunfeiRes = JSON.parse(data)

    if (xunfeiRes.code != 0) {
        log.error(`${xunfeiRes.code}: ${xunfeiRes.message}`)
        ws.close()
        return
    }

    let audio = xunfeiRes.data.audio
    let audioBuf = Buffer.from(audio, 'base64')
    
    save(audioBuf,res)

    if (xunfeiRes.code == 0 && xunfeiRes.data.status == 2) {
      res.json({
        error: 0,
        msg: '下载成功',
        path: downloadUrl
      })
      ws.close()
    }
  })

  // 资源释放
  ws.on('close', () => {
    log.info('connect close!')
  })

  // 连接错误
  ws.on('error', (err) => {
    log.error("websocket connect err: " + err)
  })
}

// 鉴权签名
function getAuthStr(date) {
  let signatureOrigin = `host: ${config.host}\ndate: ${date}\nGET ${config.uri} HTTP/1.1`
  let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, config.apiSecret)
  let signature = CryptoJS.enc.Base64.stringify(signatureSha)
  let authorizationOrigin = `api_key="${config.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`
  let authStr = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorizationOrigin))
  return authStr
}

// 保存文件
function save(data,res) {
  fs.writeFile(filePath, data, { flag: 'a' }, (err) => {
    if (err) {
      res.json({
        error: 1,
        msg: '下载失败'
      })
      log.error('save error: ' + err)
      return 
    }
  })
}

module.exports = createVoice
